package cn.donting.web.desktop.desktop;


import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import java.io.IOException;
import java.io.OutputStream;

@Component
@Log4j2
@ServerEndpoint(value = "/websocket", subprotocols = {}, configurator = WebSocket.Configurator.class)
public class WebSocket {
    private static final String HTTP_SESSION = "httpSession";

    private HttpSession httpSession;
    private Session session;

    public WebSocket() {

    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
//        session.getA
        log.info("onMessage: {}", message);
        OutputStream sendStream = session.getBasicRemote().getSendStream();
//        sendStream.write("122好家伙".getBytes(StandardCharsets.UTF_8));
//        sendStream.flush();
    }


    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        httpSession = (HttpSession) config.getUserProperties().get(HTTP_SESSION);
        this.session = session;
        log.info("link WebSocket:");
    }

    @OnClose
    public void onClose(Session session) {
        log.info("onClose: {}", session);
    }

    @OnError
    public void onError(Throwable ex) {
        log.info("onError: ", ex);
    }


    public static class Configurator extends ServerEndpointConfig.Configurator {
        @Override
        public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request,
                                    HandshakeResponse response) {
            HttpSession httpSession = (HttpSession) request.getHttpSession();
            config.getUserProperties().put(HTTP_SESSION, httpSession);
        }
    }
}
